package com.henzil.siji.weather;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.henzil.siji.bean.Weather;
import com.thoughtworks.xstream.XStream;
/**
 * @author wangjun <a
 *         href="mailto:wangjun.0112@gmail.com">wangjun.0112@gmail.com</a>
 * 
 */
public class ReadWeather {
	/**
	 * 连接网络下载数据
	 */
	public StringBuilder downData(String url) {
		HttpClient client = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		HttpGet get = new HttpGet(url);
		try {

			HttpResponse response = client.execute(get);
			HttpEntity httpEntity = response.getEntity();
			String str = EntityUtils.toString(httpEntity, "UTF-8");
			builder.append(str);
			return builder;
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 分析数据
	 */
	public Weather analysisData(StringBuilder data) {
		Log.v("weather", ""+data.lastIndexOf("</forecast_conditions>"));
		if(data!=null&&data.indexOf("<forecast_information>")>0&&data.indexOf("</forecast_conditions>", data.lastIndexOf("</forecast_conditions>"))>0)
		{
			String test="<weather>"+data.substring(data.indexOf("<forecast_information>"),data.indexOf("</forecast_conditions>", data.lastIndexOf("</forecast_conditions>")))+"</forecast_conditions></weather>";
			
			XStream xstream = new XStream();
			xstream.alias("weather", Weather.class);
			xstream.alias("forecast_information", Forecatast_information.class);
			
			xstream.alias("city", Item.class);
			xstream.alias("postal_code", Item.class);
			xstream.alias("latitude_e6", Item.class);
			xstream.alias("longitude_e6", Item.class);
			xstream.alias("forecast_date", Item.class);
			xstream.alias("current_date_time", Item.class);
			xstream.alias("unit_system", Item.class);
			
			xstream.alias("condition", Item.class);
			xstream.alias("temp_f", Item.class);
			xstream.alias("temp_c", Item.class);
			xstream.alias("humidity", Item.class);
			xstream.alias("icon", Item.class);
			xstream.alias("wind_condition", Item.class);
			
			xstream.alias("current_conditions", current_conditions.class);
			
			xstream.alias("day_of_week", Item.class);
			xstream.alias("high", Item.class);
			xstream.alias("icon", Item.class);
			xstream.alias("condition", Item.class);
			xstream.alias("low", Item.class);
			
			xstream.alias("forecast_conditions", Forecast_conditions.class);
			
			xstream.addImplicitCollection(Weather.class, "forecast_conditionses");
			
			xstream.useAttributeFor(Item.class, "data");
	
			Weather newsBrowse = new Weather();
			newsBrowse=  (Weather) xstream.fromXML(test);
			return newsBrowse;
		}else{
			return null;
		}
	}
}
